package com.bangdream.michelia.view.fragment.exam;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.contract.ExamContract;
import com.bangdream.michelia.entity.exam.AnswerBean;
import com.bangdream.michelia.entity.exam.ExamBean;
import com.bangdream.michelia.entity.exam.ExamQuestBean;
import com.bangdream.michelia.entity.exam.ExamResultDetailsBean;
import com.bangdream.michelia.entity.exam.ExamResultItemBean;
import com.bangdream.michelia.entity.exam.SubjectBean;
import com.bangdream.michelia.entity.exam.SubjectInfoBean;
import com.bangdream.michelia.presenter.ExamPresenter;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.view.activity.exam.ExamHelper;
import com.bangdream.michelia.view.activity.exam.ExamResultActivity;
import com.bangdream.michelia.view.activity.exam.OnMainActivityListener;
import com.bangdream.michelia.view.adapter.SelectExamAdapter;

import java.util.Collections;
import java.util.List;

/**
 * @date on 2018/8/18 23:16
 * @email 909732184@qq.com
 * 选择题
 */
public class SelectExamFragment extends BaseAnswerFragment<ExamContract.IExamView,ExamPresenter<ExamContract.IExamView>>
        implements View.OnClickListener,ExamContract.IExamView{
    private View view;
    private TextView tvTitle;
    //选择了哪些选项 拼接起来展示文本
    private TextView tvSelectText;
    private RecyclerView recyclerView;

    private LinearLayout btnRemember;
    private ImageView ivRemember;
    //默认不标记
    private boolean isRemember = false;
    private TextView tvIndex,tvTotalIndex,tvTime;
    private int nmIndex,nmTotalIndex;
    private SelectExamAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    //单选还是多选 默认单选
    private boolean isSingle = true;
    private SubjectBean subjectBean;
    private SubjectInfoBean data;
    //所选答案的文本描述
    private String stAnswerDescribe = "";
    //提交需要将答案中的no字段用逗号拼接提交
    private String stAnswerNos = "";
    //本次考试的考试id
    private String examId;
    //试卷id
    private String paperId;
    private OnMainActivityListener onMainActivityListener;
    private boolean isNext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.select_exam_fragment,container,false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    @Override
    public ExamPresenter createPresenter() {
        return new ExamPresenter();
    }

    @Override
    public void loadData() {
        if(subjectBean!=null) {
            mPresenter.getSubjectDetails(subjectBean.getId(),"1",pd);
        }
        setListener();
    }

    private void setListener() {
        btnRemember.setOnClickListener(this);
        adapter.setOnSelectExamItemClickListener(new SelectExamAdapter.OnSelectExamItemClickListener() {
            @Override
            public void onSelectExamItemClick(int position) {
                if(adapter.getIsSelected()==null)
                    return;
                stAnswerDescribe = "";
                stAnswerNos = "";
                String strDescribe ="";
                String[]  str1 = new String[]{"A","B","C","D","E","F","G","H","I"};
                for (int i : adapter.getIsSelected()) {
                    /*if(stAnswerDescribe.length()==0) {
                        stAnswerDescribe += adapter.getData().get(i).getDescription();
                        stAnswerNos += adapter.getData().get(i).getNo();
                    }else {
                        stAnswerDescribe += ","+adapter.getData().get(i).getDescription();
                        stAnswerNos += ","+adapter.getData().get(i).getNo();
                    }*/
                    stAnswerDescribe += adapter.getData().get(i).getDescription();
                    stAnswerNos += adapter.getData().get(i).getNo();
                    strDescribe += str1[i]+" ";
                }
                stAnswerNos = bubbleSort(stAnswerNos).toString();
                setDescribeText(strDescribe);
//                setDescribeText(position);
            }
        });
    }
    public String bubbleSort(String  stAnswerNos) {
        int[] array = new int[stAnswerNos.length()];
        for(int i=0;i<array.length;i++){
            array[i] =Integer.parseInt( stAnswerNos.substring(i,i+1));
        }
        int t = 0;
        for (int i = 0; i < array.length - 1; i++)
            for (int j = 0; j < array.length - 1 - i; j++)
                if (array[j] > array[j + 1]) {
                    t = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = t;
                }
        String str ="";
        for (int i=0;i<array.length;i++){
            String temp = String.valueOf(array[i]);
            str+=temp;
        }
//        Log.i("str----",str);
        return str;
    }
    private void init() {
        if(getArguments()!=null){
            nmIndex = getArguments().getInt("index");
            nmTotalIndex = getArguments().getInt("totalIndex");
            isSingle = getArguments().getBoolean("isSingle");
            examId = getArguments().getString("examId");
            paperId = getArguments().getString("paperId");
            subjectBean = getArguments().getParcelable("data");
        }
        tvTime = view.findViewById(R.id.tvTime);
        tvIndex = view.findViewById(R.id.tvIndex);
        tvTotalIndex = view.findViewById(R.id.tvTotalIndex);
        btnRemember = view.findViewById(R.id.btnRemember);
        ivRemember = view.findViewById(R.id.ivRemember);
        recyclerView = view.findViewById(R.id.recyclerView);
        tvTitle = view.findViewById(R.id.tvTitle);
        tvSelectText = view.findViewById(R.id.tvSelectText);
        adapter = new SelectExamAdapter(getActivity());
        adapter.setSingle(isSingle);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        pd.setCanceledOnTouchOutside(false);
    }

    private void setViewData() {
        if(data==null)
            return;
        SubjectInfoBean.QuestionInfoListBean question = data.getQuestionInfoList();
        if(question==null)
            return;

        String stTitle = question.getDescription()+"";
        String stDescribe = isSingle?"(单选题1分)":"(多选题1分)";
        SpannableStringBuilder spanableBuilder = new SpannableStringBuilder(stTitle+" "+stDescribe);
        //取出描述的位置 改变颜色为蓝色
        int length = spanableBuilder.toString().indexOf(stDescribe);
        int end = length + stDescribe.length();
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
        //如果要同时改变多处样式必须每次new一个对象
        spanableBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(MainApplication.getContext(),R.color.holo_blue_light))
                , length, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvTitle.setText(spanableBuilder);

        tvIndex.setText((nmIndex+1)+"");
        tvTotalIndex.setText("/"+nmTotalIndex+"");
        adapter.setData(data.getAnswerInfoList());
        adapter.setMaxSelectNumb(adapter.getItemCount());
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void setTime(String stTime) {
        tvTime.setText("剩余时间 "+stTime);
    }

    @Override
    public void saveAnswer(boolean isFinish,boolean isNext) {
        this.isNext = isNext;
        if(data==null||paperId==null||examId==null){
            if(isFinish){
                if(ExamHelper.getInstance().getAnswerBeans()!=null){
                    AnswerBean answerBean = new AnswerBean();
                    for (AnswerBean bean:ExamHelper.getInstance().getAnswerBeans()){
                        answerBean = bean;
                    }
                    answerBean.setIsFinish("1");
                    mPresenter.actionSubmitExam(answerBean,isFinish,pd);
                    return;
                }
            }
            showText("数据错误");
            getActivity().finish();
        }
        String tempString = stAnswerDescribe;
        L.d(tempString);
        //是否已经填写了答案
        if(tempString!=null&&tempString.length()>0) {
            ExamHelper.getInstance().getIsAnswerBegin().set(nmIndex,true);
        }else {
            ExamHelper.getInstance().getIsAnswerBegin().set(nmIndex,false);
        }
        AnswerBean answerBean = new AnswerBean();
        answerBean.setAnswer(stAnswerNos);
        answerBean.setExamId(examId);
        answerBean.setExamStart(data.getExamStart());
//        answerBean.setId(data.getId());
        Log.i("data---------",""+data.toString());
        answerBean.setPaperId(paperId);
        SubjectInfoBean.QuestionInfoListBean question = data.getQuestionInfoList();
        if(question!=null)
//        answerBean.setQuestionId(question.getId());
        answerBean.setId(subjectBean.getId());
        answerBean.setQuestionId(question.getQuestionId());
        answerBean.setUserId(AppCurrentUser.getInstance().getUserInfo().getId());
        //1：交卷 0：不交卷
        if(isFinish) {
            answerBean.setIsFinish("1");
        }else {
            answerBean.setIsFinish("0");
        }
        mPresenter.actionSubmitExam(answerBean,isFinish,pd);
        ExamHelper.getInstance().putAnswer(answerBean);
    }

    @Override
    public void setOnMainActivityListener(OnMainActivityListener onMainActivityListener) {
        this.onMainActivityListener = onMainActivityListener;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnRemember:
                setRemember();
                break;
            default:break;
        }
    }

    private void setRemember() {
        isRemember = !isRemember;
        if(isRemember){
            ivRemember.setImageResource(R.mipmap.kaoshi_bj_answer_b);
        }else {
            ivRemember.setImageResource(R.mipmap.kaoshi_bj_answer_a);
        }
        ExamHelper.getInstance().SignSetSelect(nmIndex);
    }
    //设置显示选中了哪几个答案
    private void setDescribeText(String stDescribe){
        String stTitle = "您的选择是：";
        //String stDescribe = adapter.getData().get();
        SpannableStringBuilder spanableBuilder = new SpannableStringBuilder(stTitle+" "+stDescribe);
        //取出描述的位置 改变颜色为蓝色
        int length = spanableBuilder.toString().indexOf(stDescribe);
        int end = length + stDescribe.length();
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
        //如果要同时改变多处样式必须每次new一个对象
        spanableBuilder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getActivity(),R.color.common_red))
                , length, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvSelectText.setText(spanableBuilder);
    }

    @Override
    public void setExamList(boolean isSuccess, int page, List<ExamBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectList(boolean isSuccess, List<SubjectBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectDetails(boolean isSuccess, SubjectInfoBean data, String stDescribe) {
        if(isSuccess){
            this.data = data;
            setViewData();
        }else {

        }
    }

    @Override
    public void initExamId(boolean isSuccess, String examId, String stDescribe) {

    }

    @Override
    public void actionSubmitExam(boolean isSuccess,boolean isFinish, String stDescribe) {
        if(isSuccess){
            if(isFinish){
                showText("提交成功");
                Intent intent = new Intent(getActivity(),ExamResultActivity.class);
                intent.putExtra("examId",  examId);
                startActivity(intent);
                getActivity().finish();
            }else {
                if(onMainActivityListener!=null){
                    if(isNext){
                        onMainActivityListener.onPageToNext();
                    }else {
                        onMainActivityListener.onPageToLast();
                    }
                }
            }
        }
    }

    @Override
    public void actionSubmitQuest(boolean isSuccess, boolean isFinish, String stDescribe) {

    }

    @Override
    public void setExamResultList(boolean isSuccess, List<ExamResultItemBean> data, String stDescribe) {

    }

    @Override
    public void setExamResultDetails(boolean isSuccess, ExamResultDetailsBean data, String stDescribe) {

    }

    @Override
    public void setExamQuestList(boolean isSuccess, List<ExamQuestBean> data, String stDescribe) {

    }

    @Override
    public void setExamQuList(boolean isSuccess, List<ExamBean> data, String stDescribe) {

    }
}
